<template>
  <div class="container">
    <div class="login">
      <h1>学生成绩管理系统</h1>
      <div class="form">
        <el-form :model="form" :rules="rules" size="large" ref="formRef">
          <el-form-item label="账号" prop="account">
            <el-input v-model.trim="form.account" placeholder="请输入2-8个字母" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model.trim="form.password" type="password" placeholder="请输入6-12个字母或特殊符号" show-password />
          </el-form-item>
          <el-form-item label="身份" prop="identity">
            <el-radio-group v-model="form.identity">
              <el-radio :label="1">管理员</el-radio>
              <el-radio :label="2">学生</el-radio>
              <el-radio :label="3">教师</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import useUserStore from '@/store/user.js'
import md5 from 'md5'

const rules = reactive({
  account: [
    { required: true, message: '请输入账号或用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '请输入正确格式的用户名', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 12, message: '请输入正确格式的密码', trigger: 'blur' },
  ],
  identity: [{ required: true, message: '请选择身份', trigger: 'blur' }],
})
const formRef = ref(null)
const form = ref({
  account: '',
  password: '',
  identity: 1,
})

const user = useUserStore()
const router = useRouter()
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      const password = md5(form.value.password)
      const res = await user.login({ ...form.value, password: password })
      if (res.code == 200) {
        ElMessage.success(res.msg)
        router.replace({ path: '/home' })
      } else {
        ElMessage.error(res.msg)
      }
    }
  })
}
// 重置
const resetForm = () => {
  formRef.value.resetFields()
}
</script>

<style scoped lang="scss">
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100vw;
  height: 100vh;
  background: url('@/assets/images/bag.jpg');
  .login {
    width: 500px;
    height: 500px;
    text-align: center;
    color: #fff;
    .form {
      margin-top: 50px;
      :deep(.el-form-item__label) {
        color: white;
        font-size: 18px;
      }
    }
  }
}
</style>
